/**
 * Created by wuchao on 24/2/24.
 */
$(document).ready(function () {
    $.extend($.fn.validatebox.defaults.rules, {
        Number: {
            validator: function (value, param) {
                var reg = /^[0-9]*$/;
                return reg.test(value);
            },
            message: '请输入数字'
        }
    });
    $("#rp").datagrid({
        onSelect: function (index, row) {
            changeCheck(row.roleId);
        },
    });

//            $('#tt').treegrid('append', {
//                data: [{"id": 1, "name": "1", "parentId": 1, "remark": "", "state": 1, "type": "system", "url": ""}]
//            });
});

function submitForm() {
    $.messager.progress();	// display the progress bar
    $('#ff').form('submit', {
        url: "/sec/addSecRole",
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                $.messager.progress('close');	// hide progress bar while the form is invalid
            }
            return isValid;	// return false will stop the form submission
        },
        success: function () {
            $.messager.progress('close');	// hide progress bar while submit successfully
            $('#ff').form('clear');
            $('#dd').dialog('close');
            $('#tg').treegrid('reload');
        },
        onLoadError: function () {
            $.messager.alert("保存信息", "发生错误!", "error");
        }
    });
}

function clearForm() {
    alert('clearForm');
    $('#ff').form('clear');
}

/**
 *格式化状态，如果为1，显示正常，为0显示禁用
 */
function formatStatus(value, row, index) {
    switch (value) {
        case 1:
            return '有效';
        case 0:
            return '无效';
    }
}

function formatType(value, row, index) {
    switch (value) {
        case 1:
            return 'system';
        case 0:
            return 'application';
    }
}

/*function formatParentId(value, row, index) {
 if (value == 0) {
 return '根目录';
 } else {
 return value;
 }
 }*/

var editingId;
var statusData = [{"value": "1", "text": "有效"}, {"value": "0", "text": "无效"}];
var roleTypeData = [{"value": "1", "text": "system"}, {"value": "0", "text": "application"}];
function edit() {
    if (editingId != undefined) {
        $('#tg').treegrid('select', editingId);
        return;
    }
    var row = $('#tg').treegrid('getSelected');
    if (row) {
        editingId = row.roleId
        $('#tg').treegrid('beginEdit', editingId);
    } else {
        $.messager.alert("提示", "请选择一个目录!", "info");
    }
}

function save() {
    var rowId = "";
    if (editingId != undefined) {
        $('#tg').treegrid('endEdit', editingId);
        rowId = editingId;
        editingId = undefined;
    }

    var row = $('#tg').treegrid('getSelected');
    $.post('/sec/updateSecRole/' + rowId, {
            roleId: row.roleId,
            roleNameEn: row.roleNameEn,
            roleNameZh: row.roleNameZh,
            roleType: row.roleType,
            status: row.status,
            notes: row.notes
        },
        function (resp) {
            if (resp == 'SUCCESS') {
                $('#tg').treegrid('reload');
            } else {
                alert('操作失败!');
            }
        }
    )
    ;
}

function cancel() {
    if (editingId != undefined) {
        $('#tg').treegrid('cancelEdit', editingId);
        editingId = undefined;
    }
}

//        function postData(variables) {
//            var keys = "", values = "", types = "";
//            if (variables) {
//                $.each(variables, function () {
//                    if (keys != "") {
//                        keys += ",";
//                        values += ",";
//                        types += ",";
//                    }
//                    keys += this.key;
//                    values += this.value;
//                    types += this.type;
//                });
//            }
//
//            $.post('/oa/leave/complete/', {
//                keys: keys,
//                values: values,
//                types: types
//            }, function (resp) {
//                if (resp == 'success') {
//                    $('#tg').treegrid('reload');
//                } else {
//                    alert('操作失败!');
//                }
//            });
//        }

function editRolePriv() {
    $('#rolePriv').dialog('open');
    if (editingId != undefined) {
        $('#tg').datagrid('select', editingId);
        return;
    }
    var row = $('#tg').datagrid('getSelected');
    if (row) {
        $('#rp').datagrid('appendRow', {
            roleId: row.roleId,
            roleNameEn: row.roleNameEn,
            roleNameZh: row.roleNameZh,
            roleType: row.roleType,
            status: row.status,
            notes: row.notes
        });

    } else {
        $("#rp").datagrid({url: '/sec/roleList.json'});
        $('#rp').datagrid('reload');
        row = $("#rp").datagrid("getRows")[0];
    }

    //加载模块树
    $("#tModule").tree({
        url: '/sec/roleModuleOperateTree',
        animate: true,
        checkbox: true,
        cascadeCheck: true
    });
    changeCheck(row.roleId);
}

function changeCheck(roleId) {
    $.ajax({
        method: 'GET',
        url: '/sec/roleModule?roleId=' + roleId,
        async: false,
        dataType: 'json',
        success: function (data) {
            if (data == "") {
                $('#tModule').tree('reload');
            } else {
                for (var i = 0 ; i < data.length ; i ++){
                    var node = $('#tModule').tree('find',data[i].moduleId);
                    if($('#tModule').tree('isLeaf',node.target)) {//判断是否是叶子节点
                        $('#tModule').tree('check',node.target);
                    }
                }
            }
        },
        error: function () {
            alert('error');
        }
    });
}

//function show(checkid) {
//    var s = '#check_' + checkid;
//    //alert( $(s).attr("id"));
//    // alert($(s)[0].checked);
//    /*选子节点*/
//    var nodes = $("#tModule").treegrid("getChildren", checkid);
//    for (i = 0; i < nodes.length; i++) {
//        $(('#check_' + nodes[i].id))[0].checked = $(s)[0].checked;
//
//    }
//    //选上级节点
//    if (!$(s)[0].checked) {
//        var parent = $("#tModule").treegrid("getParent", checkid);
//        $(('#check_' + parent.id))[0].checked = false;
//        while (parent) {
//            parent = $("#tModule").treegrid("getParent", parent.id);
//            $(('#check_' + parent.id))[0].checked = false;
//        }
//    } else {
//        var parent = $("#tModule").treegrid("getParent", checkid);
//        var flag = true;
//        var sons = parent.sondata.split(',');
//        for (j = 0; j < sons.length; j++) {
//            if (!$(('#check_' + sons[j]))[0].checked) {
//                flag = false;
//                break;
//            }
//        }
//        if (flag)
//            $(('#check_' + parent.id))[0].checked = true;
//        while (flag) {
//            parent = $("#tModule").treegrid("getParent", parent.id);
//            if (parent) {
//                sons = parent.sondata.split(',');
//                for (j = 0; j < sons.length; j++) {
//                    if (!$(('#check_' + sons[j]))[0].checked) {
//                        flag = false;
//                        break;
//                    }
//                }
//            }
//            if (flag)
//                $(('#check_' + parent.id))[0].checked = true;
//        }
//    }
//}
//
//function formatcheckbox(val, row) {
//    return "<input type='checkbox' onclick=show('" + row.id + "') id='check_" + row.id + "'" + (row.checked ? 'checked' : '') + "/>" + row.name;
//}
function init() {
    //去掉结点前面的文件及文件夹小图标
    $(".tree-icon,.tree-file").removeClass("tree-icon tree-file");
    $(".tree-icon,.tree-folder").removeClass("tree-icon tree-folder tree-folder-open tree-folder-closed");
}

//获取选中的结点
function getSelected() {
    var nodes = $('#tModule').tree('getChecked', ['checked', 'indeterminate']);
    var s = '';
    for (var i = 0; i < nodes.length; i++) {
        if (s != '') s += ',';
        s += nodes[i].text;
    }
    alert(s);
}

//提交submitRolePriv
function submitRolePriv() {
    var row = $('#rp').datagrid('getSelected');
    var roleId = row.roleId;
    var moduleIds = new Array();
    //获取选中和父节点
    var nodes = $('#tModule').tree('getChecked', ['checked', 'indeterminate']);
    var s = '';
    for (var i = 0; i < nodes.length; i++) {
        if (s != '') s += ',';
        s += nodes[i].text;
        moduleIds.push(nodes[i].id);
    }

    $.post('/sec/roleModuleRelatOperate/' + moduleIds + '/' + roleId, '',
        function (resp) {
            if (resp == 'SUCCESS') {
                $('#rolePriv').dialog('close');
            } else {
                alert('操作失败!');
                $('#rolePriv').dialog('close');
            }
        }
    )
    ;
}

//clearRolePriv
function clearRolePriv() {
    $('#rolePriv').dialog('close');
}